<template>
  <div v-loading="loading" class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="物料编码" prop="materialCode">
          <CodeRuleInput
            :band-value.sync="formData.materialCode"
            table-name="wms_material"
            column-name="material_code"
            :is-edit="id"
          />
        </el-form-item>
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="formData.materialName" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="规格型号">
          <el-input v-model="formData.materialModel" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="物料单位" prop="materialUnitId">
          <DictSelect
            :band-value.sync="formData.materialUnitId"
            dict-type="materialUnitId"
          />
        </el-form-item>
        <el-form-item label="物料分类" class="clickChoose" prop="materialTypeName">
          <el-input v-model="formData.materialTypeName" placeholder="请选择" readonly />
          <a class="clickChoose_button" @click.prevent="chooseType">
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item>
        <el-form-item label="物料属性">
          <DictSelect
            :band-value.sync="formData.descriptionId"
            dict-type="descriptionId"
          />
        </el-form-item>
        <el-form-item label="重量">
          <el-input v-model="formData.weight" type="number" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="材质">
          <el-input v-model="formData.texture" placeholder="请输入" clearable />
        </el-form-item>

        <el-form-item label="品牌">
          <el-input v-model="formData.brand" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="保质期(天)" prop="qualityGuaranteePeriod">
          <el-input v-model="formData.qualityGuaranteePeriod" type="number" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="最小库存量" prop="minimumInventory">
          <el-input v-model="formData.minimumInventory" type="number" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="最大库存量" prop="maximumInventory">
          <el-input v-model="formData.maximumInventory" type="number" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input
            v-if="!formData.planCode"
            v-model="formData.remark"
            maxlength="200"
            type="textarea"
            placeholder="请输入"
            show-word-limit
          />
        </el-form-item>
        <el-form-item v-if="isShow" label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="物料配图" class="double">
          <pictureUpload
            :file-names="formData.imgName"
            :file-real-names="formData.imgRealName"
            :file-urls="formData.imgUrl"
            :row-index="1"
            single-multiple="single"
            @fileName="setFileName"
          />
        </el-form-item>
        <el-form-item label="附件" class="double">
          <FileManageFull
            :file-names="formData.docFileName"
            :file-real-names="formData.docFileRealName"
            :file-urls="formData.docFileUrl"
            :row-index="1"
            @fileName="setFileName2"
          />
        </el-form-item>
        <div class="formItem_header">
          附加件信息
          <div class="formItem_header_operate">
            <a class="formItem_header_operate_item" @click="add">
              <svg-icon icon-class="新增" />
              <div class="item_name">添加</div>
            </a>
            <a class="formItem_header_operate_item delete" @click="remove">
              <svg-icon icon-class="删除" />
              <div class="item_name">删除</div>
            </a>
          </div>
        </div>
        <div ref="table_container" class="table_container">
          <el-table
            ref="table"
            :data="tableData"
            stripe
            border
            @selection-change="selectionChange"
          >
            <el-table-column type="selection" align="center" width="50" />
            <el-table-column label="物料编码" min-width="60" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span>{{ scope.row.materialCode }}</span>
              </template>
            </el-table-column>
            <el-table-column label="物料名称" min-width="60" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span>{{ scope.row.materialName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="数量" min-width="60" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-input v-model="scope.row.num" placeholder="请输入" clearable />
              </template>
            </el-table-column>
            <el-table-column label="替代料" min-width="70" prop="customerName">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.replaceMaterialName"
                  placeholder="请选择"
                  @click.native="chooseCustomer(scope.row,scope.$index)"
                />
              </template>
            </el-table-column>
            <el-table-column label="备注" width="300">
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.remark"
                  placeholder="请输入"
                  clearable
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="default"
              label="默认"
              width="80"
            >
              <template slot-scope="scope">
                <el-radio
                  v-model="tableDefaultRow"
                  :label="scope.$index"
                  @change.native="chooseDefault(scope.row,scope.$index)"
                >&nbsp;</el-radio>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button @click.stop="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script>
import {
  addOrUpdate,
  getInfo
} from '@/api/warehouseManagement/materialInfo'
import chooseTypes from '../materialType/chooseType.vue'
import searchMaterial from '@/views/warehouseManagement/materialInfo/addMaterialInfo'
import multipleChoiceMaterialType from '@/views/warehouseManagement/materialInfo/multipleChoiceMaterialType.vue'
export default {
  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {},
    isAdd: {}
  },
  data() {
    const minimumInventory = (rule, value, callback) => {
      if (value) {
        this.$refs.form.clearValidate('maximumInventory')
        if (this.formData.maximumInventory && Number(this.formData.minimumInventory) > Number(this.formData.maximumInventory)) {
          callback(new Error('最小库存量不能大于最大库存数量'))
          return
        } else if (this.formData.maximumInventory && Number(this.formData.maximumInventory) == Number(this.formData.minimumInventory)) {
          callback(new Error('最大库存量不能等于最小库存数量'))
        } else if (!this.SETTINGS.reg_no_zero.test(this.formData.minimumInventory)) {
          callback(new Error('最小库存量填写不正确'))
          return
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    const maximumInventory = (rule, value, callback) => {
      if (value) {
        this.$refs.form.clearValidate('minimumInventory')
        if (this.formData.minimumInventory && Number(this.formData.maximumInventory) < Number(this.formData.minimumInventory)) {
          callback(new Error('最大库存量不能小于最小库存数量'))
          return
        } else if (this.formData.minimumInventory && Number(this.formData.maximumInventory) == Number(this.formData.minimumInventory)) {
          callback(new Error('最大库存量不能等于最小库存数量'))
        } else if (!this.SETTINGS.reg_no_zero.test(this.formData.maximumInventory)) {
          callback(new Error('最大库存量填写不正确'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    const qualityGuaranteePeriod = (rule, value, callback) => {
      if (value) {
        if (!this.SETTINGS.reg_integer.test(this.formData.qualityGuaranteePeriod)) {
          callback(new Error('保质期只能输入整数'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      loading: true,
      isShow: false,
      pageData: {
        pageNum: 1,
        pageSize: 9999,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },
      formData: {
        materialCode: '',
        materialName: '',
        materialModel: '',
        materialUnitId: '',
        materialTypeName: '',
        materialTypeId: '',
        descriptionId: '',
        weight: '',
        texture: '',
        brand: '',
        qualityGuaranteePeriod: '',
        minimumInventory: '',
        maximumInventory: '',
        remark: '',
        status: '1',
        imgUrl: '',
        imgRealName: '',
        imgName: '',
        id: '',
        isSalePrice: '0',
        isPurchasePrice: '0',
        isEngineeringDocument: '0',
        isEngineeringBom: '0',
        docFileName: '',
        docFileRealName: '',
        docFileUrl: ''
      },
      selections: [], // 表格当前页所选中的行
      selectionsAll: [], // 表格所有页选中的行
      listData: [],
      tableData: [],
      tableHeight: '0', // 表格高度
      tableDefaultRow: null,
      peopleList: [],
      rules: {
        materialCode: [
          { required: true, message: '物料编码不能为空', trigger: 'blur' }
        ],
        materialName: [
          { required: true, message: '物料名称不能为空', trigger: 'blur' }
        ],
        materialUnitId: [
          { required: true, message: '物料单位不能为空', trigger: 'change' }
        ],
        materialTypeName: [
          { required: true, message: '物料分类不能为空', trigger: 'change' }
        ],
        minimumInventory: [
          { validator: minimumInventory, trigger: 'change' }
        ],
        maximumInventory: [
          { validator: maximumInventory, trigger: 'change' }
        ],
        qualityGuaranteePeriod: [
          { validator: qualityGuaranteePeriod, trigger: 'change' }
        ]
      }
    }
  },
  created() {
    if (!this.id) {
      this.loading = false
      // 没有id就是新增
      Object.keys(this.defaultValue).forEach((key) => {
        // 给右边数据赋值
        this.formData[key] = this.defaultValue[key]
      })
    } else {
      // 有id就是编辑
      this.getInfo()
      this.formData.id = this.id
    }
  },
  mounted() {
    // this.getList()
  },
  methods: {
    chooseCustomer(row, index) {
      this.rowIndex = index
      this.$layer.iframe({
        // 弹框
        content: {
          content: multipleChoiceMaterialType, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: row
          } // props
        },
        area: ['1320px', '700px'],
        title: '选择物料', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    chooseDefault(row, currentIndex) {
      this.tableData.forEach((ele, index) => {
        if (index == currentIndex) {
          ele.isDefault = '1'
        } else {
          ele.isDefault = '0'
        }
        return ele
      })
    },
    selectionChange(row) {
      this.selectionsAll = row
    },
    setFileName2(...data) {
      this.$set(this.formData, 'docFileName', data[0])
      this.$set(this.formData, 'docFileRealName', data[1])
      this.$set(this.formData, 'docFileUrl', data[2])
    },
    chooseType() {
      this.$layer.iframe({// 弹框
        content: {
          content: chooseTypes, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {}// props
        },
        area: ['880px', '700px'],
        title: '选择物料分类', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    showType(data) {
      this.formData.materialTypeName = data.name
      this.formData.materialTypeId = data.id
    },
    setFileName(...data) {
      this.formData.imgName = data[0]
      this.formData.imgRealName = data[1]
      this.formData.imgUrl = data[2]
    },
    getInfo() {
      getInfo(this.id).then((res) => {
        Object.keys(this.formData).forEach((key) => {
          // 给右边数据赋值
          this.formData[key] = res.data[key]
        })
        this.tableData = res.data.details
        this.tableData.forEach((ele, index) => {
          if (ele.isDefault == '1') {
            this.tableDefaultRow = index
          }
        })
        this.isShow = true
        this.loading = false
      })
    },
    add() { // 添加附加件信息
      this.$layer.iframe({
        // 弹框
        content: {
          content: searchMaterial, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: this.tableData && this.tableData.length > 0 ? this.tableData : []
          } // props
        },
        area: ['1320px', '700px'],
        title: '选择物料', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    // showMaterial(data) {
    //   data.forEach(item => {
    //     item.materialId = item.id
    //     delete item['id']
    //     item.remark = ''
    //     // data.forEach(item => {
    //     //   if (!item.isDefault) {
    //     //     item.isDefault = '0'
    //     //     data[0].isDefault = '1'
    //     //     this.tableDefaultRow = this.tableData.length
    //     //   }
    //     // })
    //   })
    //   this.tableData = data
    //   if (!this.tableData.some(item => item.isDefault == '1')) {
    //     item.isDefault = '1'
    //     this.tableDefaultRow = this.tableData.length
    //   }
    // },
    showMaterial(data) {
      console.log(data, 111111111)
      // 使用 map 函数创建新数组，避免修改原始数据
      const newData = data.map(item => {
        return {
          materialId: item.materialId,
          materialCode: item.materialCode,
          materialName: item.materialName,
          num: item.num,
          replaceMaterialName: item.replaceMaterialName,
          replaceMaterialId: item.replaceMaterialId,
          remark: item.remark,
          isDefault: item.isDefault || '0'
        }
      })

      // 查找默认项的索引
      const defaultIndex = newData.findIndex(item => item.isDefault === '1')

      // 如果不存在默认项，则设置第一个元素为默认项
      if (defaultIndex === -1 && newData.length > 0) {
        newData[0].isDefault = '1'
      }

      this.tableData = newData
      this.tableDefaultRow = defaultIndex !== -1 ? defaultIndex : 0
    },
    multipleChoiceShowMaterial(data) {
      const arr = this.$deepClone(this.tableData)
      arr[this.rowIndex].replaceMaterialName = data.materialCode + '/' + data.materialName
      arr[this.rowIndex].replaceMaterialId = data.materialId
      delete data['id']
      if (!data.materialId) {
        arr[this.rowIndex].replaceMaterialName = ''
      }
      this.tableData = arr
    },
    remove() { // 删除附加件信息
      this.selectionsAll.forEach(item => {
        this.tableData.splice(this.tableData.indexOf(item), 1)
      })
      // 找到 tableData2 里 isDefault 是 1 的 ，找到它的index
      if (this.tableData.filter(item => item.isDefault == 1).length > 0) {
        this.tableDefaultRow = this.tableData.indexOf(this.tableData.filter(item => item.isDefault == 1)[0])
      } else { // 如果 isDefault 是 1 的 被删除了
        this.tableDefaultRow = 0
      }
      this.$refs.table.clearSelection()
    },
    // 提交
    onSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.formData.details = this.tableData
          addOrUpdate(this.formData).then((res) => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.$layer.close(this.layerid) // 关闭弹框
            this.$parent.getList() // 调用父组件的刷新方法
          })
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid) // 关闭弹框
    }
  }
}
</script>

<style lang="less" scoped>
.title {
  padding-left: 20px;
  padding-bottom: 20px;
  font-size: 24px;
  width: 100%;
}
.numberComponents {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
}
/deep/ .el-input-number.is-controls-right .el-input-number__increase {
  height: 15px;
}
.el-icon-remove {
  font-size: 25px;
  color: red;
  height: 100%;
  width: 100%;
  border: 0px;
  background-color: transparent;
}
/deep/ .el-form-item__content {
  margin-left: 0 !important;
}
/deep/ .el-form-item__label {
  text-align: right;
}
.expand_radio {
  /deep/ .el-form-item__content {
    text-align: left;
  }
}
.expand_container {
  .el-form-item {
    margin-bottom: 10px;
  }
  .expand_file {
    margin-bottom: 0px;
  }

  /deep/ .el-form-item__label {
    width: 130px !important;
  }
  /deep/ .el-form-item__content {
    width: 710px !important;
  }
}
.main_main {
  .form_padding {
    padding: 0 !important;
    /deep/ .el-form-item {
      margin-right: 0px;
    }
    /deep/ .el-form-item__label {
      width: 120px !important;
    }
    /deep/ .el-form-item__content {
      width: 270px;
    }
    .remark {
      /deep/ .el-form-item__content {
        width: 690px !important;
        height: 60px;
        overflow-y: auto;
      }
    }
  }
}
/deep/ .el-table th.el-table__cell > .cell {
  position: unset;
}
/**
 * 解决el-input设置类型为number时，中文输入法光标上移问题
 **/
/deep/.el-input__inner{
  line-height: 1px !important;
}

/**
 * 解决el-input设置类型为number时，去掉输入框后面上下箭头
 **/
/deep/ input[type="number"]::-webkit-inner-spin-button, input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
</style>
